//数据库初始化
package initial

import (
	"database/sql"
	"fmt"
	//	"strconv"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/lib/pq"
	//	_ "github.com/mattn/go-sqlite3"
)

var odb orm.Ormer

/*
* 初始化数据库
*包括穿件数据库，表，以及插入部分数据
 */
func InitDB() {
	createdb()
	InitDbConnect()
	odb = orm.NewOrm()
	name := "default"
	force := true
	verbose := true
	err := orm.RunSyncdb(name, force, verbose)
	if err != nil {
		beego.Notice("init db is err ,this is %s ", err.Error())
	}

	//	insertUser()
	//	insertGroup()
	// insertRole()
	// insertNode()
	beego.Notice("database init is complete.\nPlease restart the application")
}

//数据库连接
func InitDbConnect() {
	beego.SetLogger("file", `{"filename":"logs/app.log"}`)
	dns, db_type, _, _ := getConfig(1)
	beego.Debug("数据库is %s", dns)
	err := orm.RegisterDataBase("default", db_type, dns)
	if err != nil {
		for i := 0; i < 10; i++ {
			beego.Error("数据库连接失败！失败原因：", err)
			beego.Notice("重复连接第 ", i+1, " 次！")
			time.Sleep((10 * time.Second))
			err := orm.RegisterDataBase("default", db_type, dns)
			if err == nil {
				beego.Notice("数据库连接成功： ", dns)
				break
			}
		}
	} else {
		beego.Notice("数据库连接成功： ", dns)
	}
}

/**
* 创建数据库
 */
func createdb() {
	var sqlstring string
	dns, db_type, sqlstring, db_name := getConfig(0)
	beego.Debug("\n ", dns, db_type, sqlstring)
	db, err := sql.Open(db_type, dns)
	if err != nil {
		panic(err.Error())
	}
	r, err := db.Exec(sqlstring)
	if err != nil {
		beego.Error("err is ", err.Error(), "  and r is  ", r)
	} else {
		beego.Error("Database ", db_name, " created")
	}
	defer db.Close()

}

/*
* 获取配置
	flag ==1 表示 只链接
	==0 创建 加链接
*/
func getConfig(flag int) (string, string, string, string) {
	var dns, sqlstring string
	db_type := beego.AppConfig.String("db_type")
	db_host := beego.AppConfig.String("db_host")
	db_port := beego.AppConfig.String("db_port")
	db_user := beego.AppConfig.String("db_user")
	db_pass := beego.AppConfig.String("db_pass")
	db_name := beego.AppConfig.String("db_name")
	db_path := beego.AppConfig.String("db_path")
	db_sslmode := beego.AppConfig.String("db_sslmode")
	beego.Debug("db_type is:", db_type)
	beego.Debug("db_host id :", db_host)
	if flag == 1 {
		beego.Debug("链接数据库")
		switch db_type {
		case "mysql":
			orm.RegisterDriver("mysql", orm.DRMySQL)
			dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", db_user, db_pass, db_host, db_port, db_name)
			break
		case "postgres":
			orm.RegisterDriver("postgres", orm.DRPostgres)
			//dns = fmt.Sprintf("dbname=%s host=%s  user=%s  password=%s  port=%s  sslmode=%s ", db_name, db_host, db_user, db_pass, db_port, db_sslmode)
			dns = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",db_user,db_pass,db_host,db_port,db_name,db_sslmode)
		case "sqlite3":
			orm.RegisterDriver("sqlite3", orm.DRSqlite)
			if db_path == "" {
				db_path = "./"
			}
			dns = fmt.Sprintf("%s%s.db", db_path, db_name)
			break
		default:
			beego.Error("Database driver is not allowed:", db_type)
		}

	} else {
		fmt.Println("创建数据库")
		switch db_type {
		case "mysql":
			dns = fmt.Sprintf("%s:%s@tcp(%s:%s)/?charset=utf8", db_user, db_pass, db_host, db_port)
			sqlstring = fmt.Sprintf("CREATE DATABASE  if not exists `%s` CHARSET utf8 COLLATE utf8_general_ci", db_name)
			break
		case "postgres":
			dns = fmt.Sprintf("host=%s  user=%s  password=%s  port=%s  sslmode=%s", db_host, db_user, db_pass, db_port, db_sslmode)
			sqlstring = fmt.Sprintf("CREATE DATABASE %s", db_name)
			break
			//		case "sqlite3":
			//			if db_path == "" {
			//				db_path = "./"
			//			}
			//			dns = fmt.Sprintf("%s%s.db", db_path, db_name)
			//			os.Remove(dns)
			//			sqlstring = "create table init (n varchar(32));drop table init;"
			//			break
		default:
			beego.Error("Database driver is not allowed:", db_type)
		}
	}

	return dns, db_type, sqlstring, db_name
}
